/**
 * Created by chenxq on 2017/12/22.
 */
import React,{PureComponent} from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Table, Card, Button ,Form ,Input ,Row ,Col ,Select ,Popconfirm ,Modal ,message ,Divider,DatePicker,Radio,Dropdown,Menu} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../TableList.less';
import {listParams,payTypes,signStatus} from '../defaultData';
import {findObjByKey ,convertLongToString} from '../../utils/index';
import DescriptionList from '../../components/DescriptionList';
import Assign from '../../components/Sign/Assign';
import { Link, Route, Redirect, Switch, routerRedux } from 'dva/router';

const FormItem = Form.Item;
const { Option } = Select;
const {RangePicker} = DatePicker;
const {Description} =DescriptionList;

@connect(state=>({
  sign:state.sign,
  userManage:state.usermanagement,
  product:state.product
}))
@Form.create()
export default class extends PureComponent{
  constructor(props){
    super(props);
    let state=this.props.state;
    this.state={
      pagination:{
        ...listParams,
        state
      },
      visible:false,
      editObj:{},
      key:Math.random(),
      loanId:0
    }
  }

  columns=[{
    title:'客户姓名',
    dataIndex:'customerName'
  },{
    title:'产品',
    dataIndex:'productId',
    render:(productId)=>{
      let proList=this.props.product.allList || [];
      let obj=proList.find(item=>item.id==productId) || {};
      return obj.name || '';
    }
  },{
    title:'支付方式',
    dataIndex:'payWay',
    render(payWay){
      return payWay? findObjByKey(payTypes,payWay).name :''
    }
  },{
    title:'状态',
    dataIndex:'state',
    render(state){
      return state? findObjByKey(signStatus,state).name :''
    }
  },{
    title:'跟进人',
    dataIndex:'assignedTo',
    render:(id)=>{
      let userList=this.props.userManage.allList || [];
      if(!id){
        return '';
      }
      let user=userList.find(item=>item.id==id) || {};
      return user.userName;
    }
  },{
    title:'批复额度',
    dataIndex:'replyQuotas',
    render(val){
      return ((val || 0)/100).toFixed(2)
    }
  },{
    title:'批复利息',
    dataIndex:'replyInterest',
    render(val){
      return ((val || 0)/100).toFixed(2)
    }
  },{
    title:'批复周期',
    dataIndex:'replyPeriod'
  },{
    title: '创建时间',
    dataIndex: 'createdTime',
    render:(createdTime)=>{
      return createdTime? convertLongToString(createdTime) : '';

    }
  },{
    title: "操作",
    dataIndex: "id",
    render: (id,record) =>
      <div className="operations">
        {/*<a onClick={this.showDetail.bind(this,record)}>详情</a>*/}
        <Link to={`/sign/detail/${record.id}`}>详情</Link>
        <Divider type="vertical"/>
        <a onClick={this.showAssign.bind(this,record)}>操作</a>
        <Divider type="vertical"/>
        <Popconfirm title="确定要删除该签单" onConfirm={this.remove.bind(this,record.id)}>
          <a>删除</a>
        </Popconfirm>
      </div>
  }];

  showAssign=(record)=>{
    this.setState({
      editObj:{...record},
      visible:true,
      key:Math.random()
    })
  }
  getProName=(id,arr)=>{
    let obj=arr.find(item=>item.id==id) || {};
    return obj.name || '';
  }
  getUserName=(id,arr)=>{
    let obj= arr.find(item=>item.id==id) || {};
    return obj.userName || '';
  }
  remove=(id)=>{
    let _this=this;
    this.props.dispatch({
      type:'sign/fetchRemove',
      payload:{id}
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('删除成功',0.8,()=>{
          _this.getList();
        })
      }else{
        message.error(jsonData.msg);
      }
    })
  }

  handleCancel=()=>{
    this.setState({
      visible:false
    })
  }


  handleSearch=(e)=>{
    e.preventDefault();
    let values=this.props.form.getFieldsValue();
    let times=values.searchTime;
    let start=null,
        end=null;
    if(times.length==2){
      start=times[0].format('X');
      end=times[1].format('X')
    }
    let params={
      ...values,
      start,
      end
    }
    delete params.searchTime;
    console.log(params,'params');
    params.current=1;
    this.setState({
      pagination:Object.assign(this.state.pagination,params)
    },()=>{
      this.getList();
    })
  }

  getList=(page={current:1})=>{
    let pagination=this.state.pagination;
    this.props.dispatch({
      type:'sign/fetchList',
      payload:Object.assign({},pagination,page)
    })
  }
  renderForm=()=>{
    const { getFieldDecorator } = this.props.form;
    let userList=this.props.userManage.allList || [];
    return (<Form onSubmit={this.handleSearch} layout="inline" className="ant-advanced-search-form">
      <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
        <Col md={6}>
          <FormItem label="客户编号" >
            {getFieldDecorator('customerId')(
              <Input placeholder="请输入客户编号" />
            )}
          </FormItem>
        </Col>
        <Col md={6}>
          <FormItem label="指派人" >
            {getFieldDecorator('assignTo')(
              <Select mode="combobox"
                      placeholder="请选择"
                      optionFilterProp="children"
                      optionLabelProp="children">
                {userList.map(item=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
              </Select>
            )}
          </FormItem>
        </Col>
        {/*<Col md={8}>
          <FormItem label="签单状态" >
            {getFieldDecorator('state')(
              <Select placeholder="请选择" style={{ width: '100%' }}>
                <Option value={null}>请选择</Option>
                {
                  signStatus.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)
                }
              </Select>
            )}
          </FormItem>
        </Col>*/}
        <Col md={10}>
          <FormItem label="起止时间" >
            {getFieldDecorator('searchTime',{
              rules: [{ type: 'array', required: false, message: 'Please select time!' }],
            })(
              <RangePicker />
            )}
          </FormItem>
        </Col>
        <Col md={1} sm={24}>
          <FormItem >
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
            </span>
          </FormItem>
        </Col>

      </Row>
      <Row gutter={{ md: 24, lg: 24, xl: 24 }} >

      </Row>
    </Form>)
  }

  componentDidMount(){
    this.getList();
    this.props.dispatch({
      type:'usermanagement/fetchAllList',
      payload:{}
    })
  }
  render(){
    return (<PageHeaderLayout title="签单列表">
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
            {this.renderForm()}
          </div>
          <div style={{marginTop: "20px"}}>
            <Table rowKey="id"
                   loading={this.props.sign.loading}
                   columns={this.columns}
                   pagination={{...this.state.pagination,total:this.props.sign.total}}
                   dataSource={this.props.sign.list}
                   onChange={this.getList}
            />
          </div>
        </div>
      </Card>
      <Assign visible={this.state.visible}
              key={this.state.key}
              signObj={this.state.editObj}
              onCancel={this.handleCancel}
              onSubmit={()=>{
                this.setState({
                  visible:false
                })
                this.getList()
              }}/>
    </PageHeaderLayout>)
  }
}
